#include "listnode.h"
// https://leetcode.cn/problems/add-two-numbers/
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2)
{

    struct ListNode* head = NULL;
    struct ListNode* tail = NULL;
    int carry = 0;
    int sum = 0;
    int v1 = 0;
    int v2 = 0;
    while (l1 || l2)
    {
        v1 = l1 ? l1->val : 0;
        v2 = l2 ? l2->val : 0;
        sum = v1 + v2 + carry;
        if (!head)
        {
            head = tail = (struct ListNode*)malloc(sizeof(struct ListNode));
            tail->val = sum % 10;
            tail->next = NULL;
        }
        else
        {
            tail->next = (struct ListNode*)malloc(sizeof(struct ListNode));
            tail->next->val = sum % 10;
            tail = tail->next;
            tail->next = NULL;
        }
        carry = sum / 10;

        if (l1)
        {
            l1 = l1->next;
        }
        if (l2)
        {
            l2 = l2->next;
        }
    }

    if (carry)
    {
        tail->next = (struct ListNode*)malloc(sizeof(struct ListNode));
        tail->next->val = carry;
        tail = tail->next;
        tail->next = NULL;
    }
    return head;
}